package com.sunzhe.member.config;

import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.member.annotation.LoginRequired;
import com.ibeetl.member.entity.Member;
import com.ibeetl.member.service.MemberService;
import com.sunzhe.member.service.PlatformService;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 在此类中增加拦截器
 * @author Administrator
 *
 */
@Configuration
public class MemberMVCConf implements WebMvcConfigurer, InitializingBean {

    @Autowired
    Environment env;

    @Autowired
    MemberService memberService;
    @Autowired
    PlatformService platformService;

    @Autowired
    BeetlGroupUtilConfiguration beetlGroupUtilConfiguration;

    @Autowired
    HttpRequestLocal httpRequestLocal;

    @Autowired
    GroupTemplate groupTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new AuthInterceptor(httpRequestLocal,this)).addPathPatterns("/**").excludePathPatterns("/plugins/**","/css/**","/js/**","/img/**"); 
        // super.addInterceptors(registry);

    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
    	
    }


    @Override
    public void afterPropertiesSet() throws Exception {
       
    }


}

class AuthInterceptor implements HandlerInterceptor {
	
	MemberMVCConf conf;
    HttpRequestLocal httpRequestLocal;

    public AuthInterceptor(HttpRequestLocal httpRequestLocal, MemberMVCConf conf) {
        this.conf = conf;
        this.httpRequestLocal = httpRequestLocal;
    }
    
	/**
     * 在请求处理之前进行调用（Controller方法调用之前）
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	// 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodAnnotation != null) {
            // 判断是否存在令牌信息，如果存在，则允许登录
        	Member member = conf.platformService.getCurrentMember(request.getSession());
            if (null == member) {
            	response.sendRedirect("/");
            	return false;
                //throw new RuntimeException("未登录，请重新登录");
            }
            member = conf.memberService.getMemberById(member.getId());
            if (member == null) {
            	response.sendRedirect("/");
            	return false;
                //throw new RuntimeException("用户不存在，请重新登录");
            }
            // 当前登录用户@CurrentUser
            request.setAttribute(PlatformService.ACCESS_CURRENT_MEMBER, member);
            return true;
        }
    	return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

